package model.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class ZippingUtil {
	
	public void unzip(String zipFile) throws ZipException, IOException 
	{
	
			System.out.println(zipFile);
			int BUFFER = 2048;
			File file = new File(zipFile);
			ZipFile zip = new ZipFile(file);
			String newPath =  file.getParentFile().getAbsolutePath() ;
			
			BufferedOutputStream dest = null ;
			FileOutputStream fos = null ;
			BufferedInputStream is = null ;
			
			Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();
			
		 try
		 {		
			while (zipFileEntries.hasMoreElements()) 
			{
			    ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
			    String currentEntry = entry.getName();
			    File destFile = new File(newPath, currentEntry);
			    destFile = new File(newPath, destFile.getName());
			    File destinationParent = destFile.getParentFile();
			    
			    dest = null ;
			    fos = null ;
			    is = null ;
			    
			    destinationParent.mkdirs();
			    if (!entry.isDirectory()) 
			    {
			            is = new BufferedInputStream(zip.getInputStream(entry));
			            int currentByte;
			            byte data[] = new byte[BUFFER];        
			            fos = new FileOutputStream(destFile);
			            dest = new BufferedOutputStream(fos,BUFFER);
			            while ((currentByte = is.read(data, 0, BUFFER)) != -1) 
			            {
			                  dest.write(data, 0, currentByte);
			            }
			            dest.flush();
			            dest.close();
			            fos.close();
			            is.close();
			    }
			    if (currentEntry.endsWith(".zip")) {
			            
			            unzip(destFile.getAbsolutePath());
			    }
			}	
				zip.close();
		}	
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
            if(dest!=null)
            {
            	dest.flush();
                dest.close();
            }
            if(fos!=null)  fos.close();
            if(is!=null)  is.close();
		}
		
}

}
